package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.AutherWorksTable;
import com.web.exiaodao.business.repository.AutherWorksTableRepository;
import com.web.exiaodao.business.service.AutherWorksTableService;
import com.web.exiaodao.remote.vo.ArtInformationVo;
import com.web.exiaodao.remote.vo.AutherWorksTableVo;

@Service("AutherWorksTableService")
@Transactional(readOnly = false)
public class AutherWorksTableServiceImpl extends BaseService<AutherWorksTable> implements AutherWorksTableService {

	private static final Logger LOGGER = Logger.getLogger(AutherWorksTableServiceImpl.class);

	@Autowired
	private AutherWorksTableRepository autherWorksTableRepository;
	
	/**
	 * 查询单条AutherWorksTable信息
	 * //@param tId
	 * @return 返回单个AutherWorksTable对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<AutherWorksTable> findOne(Long modelId) throws BusinessException {
		AutherWorksTable obj = new AutherWorksTable();
		if(modelId != 0){
			obj = autherWorksTableRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<AutherWorksTable> xr = new XaResult<AutherWorksTable>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->AutherWorksTable");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的AutherWorksTable数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象AutherWorksTable集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<AutherWorksTable>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<AutherWorksTable> page = autherWorksTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), AutherWorksTable.class), pageable);
		XaResult<Page<AutherWorksTable>> xr = new XaResult<Page<AutherWorksTable>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->AutherWorksTable");
		return xr;
	}

	/**
	 * 分页查询状态status的AutherWorksTable数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象AutherWorksTable集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<AutherWorksTable>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<AutherWorksTable> page = autherWorksTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), AutherWorksTable.class), pageable);
		XaResult<Page<AutherWorksTable>> xr = new XaResult<Page<AutherWorksTable>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->AutherWorksTable");
		return xr;
	}

	/**
	 * 保存AutherWorksTable信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<AutherWorksTable> saveOrUpdate(AutherWorksTable model) throws BusinessException {
		AutherWorksTable obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = autherWorksTableRepository.findOne(model.getId());
		}else{
			obj = new AutherWorksTable();
		}
	    obj.setWorksName(XaUtil.isNotEmpty(model.getWorksName()) ? model.getWorksName() : obj.getWorksName());
	    obj.setAutherID(XaUtil.isNotEmpty(model.getAutherID()) ? model.getAutherID() : obj.getAutherID());
	    obj.setWorksPrice(XaUtil.isNotEmpty(model.getWorksPrice()) ? model.getWorksPrice() : obj.getWorksPrice());
	    obj.setWorksIntroduce(XaUtil.isNotEmpty(model.getWorksIntroduce()) ? model.getWorksIntroduce() : obj.getWorksIntroduce());
	    obj.setWorksImgs(XaUtil.isNotEmpty(model.getWorksImgs()) ? model.getWorksImgs() : obj.getWorksImgs());
	    obj.setWorksInventory(XaUtil.isNotEmpty(model.getWorksInventory()) ? model.getWorksInventory() : obj.getWorksInventory());
	    obj.setWorksDeposit(XaUtil.isNotEmpty(model.getWorksDeposit()) ? model.getWorksDeposit() : obj.getWorksDeposit());
	    obj.setClickCont(XaUtil.isNotEmpty(model.getClickCont()) ? model.getClickCont() : obj.getClickCont());
        obj.setSort(XaUtil.isNotEmpty(model.getSort()) ? model.getSort() : obj.getSort());
	    obj = autherWorksTableRepository.save(obj);
		XaResult<AutherWorksTable> xr = new XaResult<AutherWorksTable>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改AutherWorksTable状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回AutherWorksTable对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<AutherWorksTable> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<AutherWorksTable> xr = new XaResult<AutherWorksTable>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				AutherWorksTable obj = autherWorksTableRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = autherWorksTableRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	/**
	 * 分页查询AutherWorksTable
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Page<AutherWorksTableVo>> findAutherWorksList(
			Pageable pageable, Map<String, Object> filterParams)
			throws BusinessException {
		StringBuffer sql = new StringBuffer("SELECT a.id,a.works_name,ar.author_name,a.works_price,a.works_introduce,a.works_imgs,a.create_time,a.`works_inventory`,a.works_deposit,a.sort,a.click_cont ");
		sql.append("FROM `tb_xa_autherworkstable` a ");
		sql.append("LEFT JOIN `tb_xa_artinformation` ar ON a.autherid = ar.id ");
		sql.append("WHERE a.status<>").append(XaConstant.Status.delete);
		StringBuffer sql1 = new StringBuffer("select count(*) ");
		sql1.append("FROM `tb_xa_autherworkstable` a ");
		sql1.append("LEFT JOIN `tb_xa_artinformation` ar ON a.autherid = ar.id ");
		sql1.append("WHERE a.status<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_WorksName"))){
			sql.append(" AND a.works_name ").append(" like '%").append(filterParams.get("LIKE_WorksName")).append("%' ");
			sql1.append(" AND a.works_name ").append(" like '%").append(filterParams.get("LIKE_WorksName")).append("%' ");
		}
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_AutherID"))){
			sql.append(" AND ar.author_name ").append(" like '%").append(filterParams.get("LIKE_AutherID")).append("%' ");
			sql1.append(" AND ar.author_name ").append(" like '%").append(filterParams.get("LIKE_AutherID")).append("%' ");
		}
		sql.append(" ORDER BY a.sort ASC,a.click_cont DESC,a.create_time desc");
		sql1.append(" ORDER BY a.sort ASC,a.click_cont DESC,a.create_time desc");
		List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<AutherWorksTableVo> vos = new ArrayList<AutherWorksTableVo>();
		for (Object[] obj : objs) {
			AutherWorksTableVo vo = new AutherWorksTableVo();
			ArtInformationVo aVo = new ArtInformationVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setWorksName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			aVo.setAuthorName(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setWorksPrice(XaUtil.isEmpty(obj[3])?0:Double.valueOf(obj[3].toString()));
			vo.setWorksIntroduce(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
			if(XaUtil.isEmpty(obj[5])){
				vo.setWorksImgs1(null);
			}else{
				String imgs = XaUtil.isEmpty(obj[5])?"":obj[5].toString();
				String[] arr = imgs.split(",");
				List<String> list = java.util.Arrays.asList(arr);
				vo.setWorksImgs1(list);
			}
			vo.setCreateTime(XaUtil.isEmpty(obj[6])?"":obj[6].toString());
			vo.setWorksInventory(XaUtil.isEmpty(obj[7])?0:Long.valueOf(obj[7].toString()));
			vo.setWorksDeposit(XaUtil.isEmpty(obj[8])?0:Double.valueOf(obj[8].toString()));
			vo.setSort(XaUtil.isEmpty(obj[9])?0:Long.valueOf(obj[9].toString()));
			vo.setClickCont(XaUtil.isEmpty(obj[10])?0:Long.valueOf(obj[10].toString()));
			vo.setArtInformationVo(aVo);
			vos.add(vo);
		}
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		int count=Integer.parseInt(obj1.get(0)+"");	
		Page<AutherWorksTableVo> page= new MyPage<AutherWorksTableVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		XaResult<Page<AutherWorksTableVo>> xr=new XaResult<Page<AutherWorksTableVo>>();
		xr.setObject(page);
		return xr;
	}

	//根据ID查询作品
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<AutherWorksTableVo> findAutherWorksTableById(Long modelId)
			throws BusinessException {
		AutherWorksTable obj = new AutherWorksTable();
		AutherWorksTableVo vo = new AutherWorksTableVo();
		vo.setAutherWorksTable(obj);
		String sql = "SELECT id,author_name FROM `tb_xa_artinformation` WHERE status<>"+XaConstant.Status.delete;
		List<Object[]> objs=this.query(sql, null, null);
		List<ArtInformationVo> vos = new ArrayList<ArtInformationVo>();
		String o = null;
		for (Object[] obj1 : objs) {	
			ArtInformationVo avo = new ArtInformationVo();
			avo.setId(Long.valueOf(obj1[0].toString()));
			o = XaUtil.isEmpty(obj1[1])?"":obj1[1].toString();
			avo.setAuthorName(o);
			vos.add(avo);
		}
		vo.setArtList(vos);
		if(modelId != 0){
			obj = autherWorksTableRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
			vo.setAutherWorksTable(obj);
			if(XaUtil.isNotEmpty(obj.getWorksImgs())){
				String imgs = obj.getWorksImgs();
				String[] arr = imgs.split(",");
				List<String> list = java.util.Arrays.asList(arr);
				vo.setWorksImgs1(list);
			}
			
			vo.setArtList(vos);
			vo.setArtName(o);
		}
		XaResult<AutherWorksTableVo> xr = new XaResult<AutherWorksTableVo>();
		if (XaUtil.isNotEmpty(vo)) {
			xr.setObject(vo);
			LOGGER.info("后台----->查询单个实体----->AutherWorksTable");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}
	
}
